package model

import (
	"database/sql"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
)

func BonusConfigUpdate(id string, data TblBonusConfig) error {

	record := g.Record{
		"recharge_amount_lv1": data.RechargeAmountLv1,
		"rate_amount_lv1":     data.RateAmountLv1,
		"recharge_amount_lv2": data.RechargeAmountLv2,
		"rate_amount_lv2":     data.RateAmountLv2,
		"recharge_amount_lv3": data.RechargeAmountLv3,
		"rate_amount_lv3":     data.RateAmountLv3,
		"lvl_one_rebate":      data.LvlOneRebate,
		"lvl_two_rebate":      data.LvlTwoRebate,
		"lvl_three_rebate":    data.LvlThreeRebate,
	}
	query, _, _ := dialect.Update("tbl_bonus_config").Set(&record).Where(g.Ex{"id": id}).ToSQL()

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return nil
}

func BonusConfigList(page, pageSize uint, ex g.Ex) (BonusConfigData, error) {

	data := BonusConfigData{}
	t := dialect.From("tbl_bonus_config")
	if page >= 1 {
		query, _, _ := t.Select(g.COUNT(1)).Where(ex).ToSQL()

		err := meta.MerchantDB.Get(&data.T, query)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	offset := (page - 1) * pageSize
	query, _, _ := t.Select(colsBonusConfig...).Where(ex).Offset(offset).Limit(pageSize).Order(g.C("id").Asc()).ToSQL()

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	data.S = pageSize
	return data, nil
}
